/*
 * Copyright (c) 2012-2014 The original author or authors
 * ------------------------------------------------------
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * and Apache License v2.0 which accompanies this distribution.
 *
 * The Eclipse Public License is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * The Apache License v2.0 is available at
 * http://www.opensource.org/licenses/apache2.0.php
 *
 * You may elect to redistribute this code under either of these licenses.
 */
package org.dna.mqtt.moquette.processor.impl;

import org.dna.mqtt.moquette.messaging.spi.impl.ValueEvent;
import org.dna.mqtt.moquette.messaging.spi.impl.events.OutputMessagingEvent;
import org.dna.mqtt.moquette.proto.messages.AbstractMessage;
import org.dna.mqtt.moquette.proto.messages.PubRecMessage;
import org.dna.mqtt.moquette.proto.messages.PubRelMessage;
import org.dna.mqtt.moquette.server.ServerChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author puran
 */
public class PubRecProcessor extends AbstractProtocolProcessor {
	private static final Logger LOG = LoggerFactory.getLogger(PubRecProcessor.class);
	
	public PubRecProcessor(ServerChannel session, PubRecMessage message) {
		super(session, message);
	}

	public void processEvent(ValueEvent valueEvent) {
		ServerChannel session = getSession();
		PubRecMessage message = (PubRecMessage)getMessage();
		
		 //once received a PUBREC reply with a PUBREL(messageID)
        LOG.debug("\t\tSRV <--PUBREC-- SUB processPubRec invoked for clientID {} ad messageID {}", session.getClientID(), message.getMessageID());
        
        PubRelMessage pubRelMessage = new PubRelMessage();
        pubRelMessage.setMessageID(message.getMessageID());
        pubRelMessage.setQos(AbstractMessage.QOSType.LEAST_ONE);
        
        ServerChannel clientSession = getBaseProcessor().getClientSession(session.getClientID());
        getBaseProcessor().disruptorPublish(new OutputMessagingEvent(clientSession, pubRelMessage));
	}
}
